﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DiscreteMath
{
    public class RegularGrammar : ContextFreeGrammar, ILanguageOperator<ContextFreeGrammar>
    {
        public RegularGrammar(
            ISet<char> nonterminals,
            ISet<string> terminals,
            RuleDictionary rules,
            char startSymbol) :
            base(nonterminals, terminals, rules, startSymbol)
        {

        }

        public static ContextFreeGrammar FromRegex(string regex)
        {
            if (string.IsNullOrEmpty(regex))
                throw new ArgumentException("string is null or empty", "regex");

            ContextFreeGrammar grammar =
                RpnConverter<ContextFreeGrammar>.EvaluateRegex(regex, CreateSingleLetterGrammar);

            return grammar;
        }

        private static ContextFreeGrammar CreateSingleLetterGrammar(char letter, ISet<char> alphabet)
        {
            Random rng = new Random();
            char startSymbol = (char)rng.Next(UnicodeEncoding.CharSize * 8);
            var nonterminals = new HashSet<char>() { startSymbol };
            var terminals = alphabet.Select(x => x.ToString()).ToSet();
            var rules = new RuleDictionary()
            {
                { startSymbol, new List<string>() { letter.ToString() } },
            };

            var grammar = new RegularGrammar(nonterminals, terminals, rules, startSymbol);

            return grammar;
        }
    }
}
